import {createRouter, createWebHistory} from 'vue-router';
import {isAiReplying} from "@/utils/aiChat";
import store from "@/store";

const routes = [
    {
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        component: () => import('@/views/chat')
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 注册一个全局前置守卫,确保要调用 next 方法，否则钩子就不会被 resolved
router.beforeEach((to, from, next) => {
    const newPath = checkRouter(to.path)
    if (to.path !== newPath) {
        if (from.path === newPath) {
            next(false)
            return;
        }

        next(newPath)
        return
    }

    // AI是否正在回复时，不允许跳转
    if (isAiReplying()) {
        next(false)
        return;
    }

    next()
})

// 白名单
const whiteList = ['/user/agentPoster']

// 判断能否跳转
export const checkRouter = (path) => {
    if (whiteList.includes(path)) {
        return path
    }

    // 未登录时不能进入所有二级页面
    if (!store.getters["user/isLogin"]) {
        const array = path.split(`/`)
        if (array.length >= 3) {
            return `/${array[1]}`
        }
    }

    return path
}

export default router;
